from rest_framework import status
from rest_framework.decorators import api_view, permission_classes, parser_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from django.core.mail import send_mail
from django.core.cache import cache
from django.conf import settings
import random
import string
from .models import User
from .serializers import (
    UserSerializer,
    RegisterSerializer,
    LoginSerializer,
    ChangePasswordSerializer,
    UserUpdateSerializer,
    SendVerificationCodeSerializer,
    EmailCodeLoginSerializer,
    ResetPasswordSerializer
)


@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    """用户注册"""
    serializer = RegisterSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.save()
        return Response({
            'success': True,
            'message': '注册成功！请登录',
            'data': {
                'user_id': user.id,
                'name': user.name,
                'email': user.email
            }
        }, status=status.HTTP_201_CREATED)
    
    return Response({
        'success': False,
        'message': '注册失败',
        'errors': serializer.errors
    }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    """用户登录"""
    serializer = LoginSerializer(data=request.data)
    if not serializer.is_valid():
        return Response({
            'success': False,
            'message': '请提供邮箱和密码'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    email = serializer.validated_data['email']
    password = serializer.validated_data['password']
    
    # 使用email进行认证
    user = authenticate(request, username=email, password=password)
    
    if user is None:
        return Response({
            'success': False,
            'message': '邮箱或密码错误'
        }, status=status.HTTP_401_UNAUTHORIZED)
    
    if not user.is_active:
        return Response({
            'success': False,
            'message': '账号已被禁用'
        }, status=status.HTTP_403_FORBIDDEN)
    
    # 生成JWT Token
    refresh = RefreshToken.for_user(user)
    user_data = UserSerializer(user, context={'request': request}).data
    
    return Response({
        'success': True,
        'message': '登录成功！',
        'data': {
            'token': str(refresh.access_token),
            'refresh': str(refresh),
            'user': user_data
        }
    })


@api_view(['POST'])
@permission_classes([AllowAny])
def send_verification_code(request):
    """发送邮箱验证码"""
    serializer = SendVerificationCodeSerializer(data=request.data)
    if not serializer.is_valid():
        return Response({
            'success': False,
            'message': '请提供有效的邮箱地址',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)
    
    email = serializer.validated_data['email']
    
    # 生成6位数字验证码
    code = ''.join(random.choices(string.digits, k=6))
    
    # 将验证码存储到缓存中，有效期5分钟
    cache_key = f'email_code_{email}'
    cache.set(cache_key, code, 300)  # 300秒 = 5分钟
    
    # 发送邮件
    try:
        send_mail(
            subject='AI故事生成器 - 登录验证码',
            message=f'您的登录验证码是：{code}\n\n验证码有效期为5分钟，请勿泄露给他人。',
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[email],
            fail_silently=False,
        )
        
        return Response({
            'success': True,
            'message': '验证码已发送到您的邮箱，请查收'
        })
    except Exception as e:
        return Response({
            'success': False,
            'message': f'验证码发送失败：{str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([AllowAny])
def email_code_login(request):
    """邮箱验证码登录"""
    serializer = EmailCodeLoginSerializer(data=request.data)
    if not serializer.is_valid():
        return Response({
            'success': False,
            'message': '请提供邮箱和验证码',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)
    
    email = serializer.validated_data['email']
    code = serializer.validated_data['code']
    
    # 从缓存中获取验证码
    cache_key = f'email_code_{email}'
    cached_code = cache.get(cache_key)
    
    if not cached_code:
        return Response({
            'success': False,
            'message': '验证码已过期或不存在，请重新获取'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    if cached_code != code:
        return Response({
            'success': False,
            'message': '验证码错误'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证码正确，查找用户
    try:
        user = User.objects.get(email=email)
    except User.DoesNotExist:
        return Response({
            'success': False,
            'message': '该邮箱未注册'
        }, status=status.HTTP_404_NOT_FOUND)
    
    if not user.is_active:
        return Response({
            'success': False,
            'message': '账号已被禁用'
        }, status=status.HTTP_403_FORBIDDEN)
    
    # 删除已使用的验证码
    cache.delete(cache_key)
    
    # 生成JWT Token
    refresh = RefreshToken.for_user(user)
    user_data = UserSerializer(user, context={'request': request}).data
    
    return Response({
        'success': True,
        'message': '登录成功！',
        'data': {
            'token': str(refresh.access_token),
            'refresh': str(refresh),
            'user': user_data
        }
    })


@api_view(['POST'])
@permission_classes([AllowAny])
def reset_password(request):
    """重置密码"""
    serializer = ResetPasswordSerializer(data=request.data)
    if not serializer.is_valid():
        return Response({
            'success': False,
            'message': '请提供邮箱和验证码',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)
    
    email = serializer.validated_data['email']
    code = serializer.validated_data['code']
    new_password = serializer.validated_data['new_password']
    
    # 从缓存中获取验证码
    cache_key = f'email_code_{email}'
    cached_code = cache.get(cache_key)
    
    if not cached_code:
        return Response({
            'success': False,
            'message': '验证码已过期或不存在，请重新获取'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    if cached_code != code:
        return Response({
            'success': False,
            'message': '验证码错误'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    # 验证码正确，查找用户并重置密码
    try:
        user = User.objects.get(email=email)
    except User.DoesNotExist:
        return Response({
            'success': False,
            'message': '该邮箱未注册'
        }, status=status.HTTP_404_NOT_FOUND)
    
    if not user.is_active:
        return Response({
            'success': False,
            'message': '账号已被禁用'
        }, status=status.HTTP_403_FORBIDDEN)
    
    # 重置为用户设置的新密码
    user.set_password(new_password)
    user.save()
    
    # 删除已使用的验证码
    cache.delete(cache_key)
    
    return Response({
        'success': True,
        'message': '密码重置成功，请使用新密码登录'
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def logout(request):
    """用户登出"""
    return Response({
        'success': True,
        'message': '登出成功！'
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_current_user(request):
    """获取当前用户信息"""
    serializer = UserSerializer(request.user, context={'request': request})
    return Response({
        'success': True,
        'data': serializer.data
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_user_list(request):
    """获取用户列表（管理员权限）"""
    # 检查是否为管理员
    if request.user.role != 'admin':
        return Response({
            'success': False,
            'message': '无权限访问用户列表'
        }, status=status.HTTP_403_FORBIDDEN)
    
    # 获取所有活跃用户
    users = User.objects.filter(is_active=True).order_by('-created_at')
    serializer = UserSerializer(users, many=True, context={'request': request})
    
    return Response({
        'success': True,
        'data': serializer.data
    })


@api_view(['GET'])
@permission_classes([AllowAny])
def get_user_profile(request, user_id):
    """获取用户资料"""
    try:
        user = User.objects.get(id=user_id)
        serializer = UserSerializer(user, context={'request': request})
        return Response({
            'success': True,
            'data': serializer.data
        })
    except User.DoesNotExist:
        return Response({
            'success': False,
            'message': '用户不存在'
        }, status=status.HTTP_404_NOT_FOUND)


@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def update_profile(request, user_id):
    """更新用户资料"""
    if request.user.id != user_id and request.user.role != 'admin':
        return Response({
            'success': False,
            'message': '无权限修改其他用户信息'
        }, status=status.HTTP_403_FORBIDDEN)
    
    try:
        user = User.objects.get(id=user_id)
        serializer = UserUpdateSerializer(user, data=request.data, partial=True)
        
        if serializer.is_valid():
            serializer.save()
            user_data = UserSerializer(user, context={'request': request}).data
            return Response({
                'success': True,
                'message': '资料更新成功！',
                'data': user_data
            })
        
        return Response({
            'success': False,
            'message': '更新失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)
    except User.DoesNotExist:
        return Response({
            'success': False,
            'message': '用户不存在'
        }, status=status.HTTP_404_NOT_FOUND)


@api_view(['PUT', 'PATCH'])
@permission_classes([IsAuthenticated])
@parser_classes([MultiPartParser, FormParser])
def update_current_user_profile(request):
    """更新当前登录用户的资料（支持文件上传）"""
    user = request.user
    
    try:
        # 获取数据
        name = request.data.get('name')
        bio = request.data.get('bio')
        avatar = request.FILES.get('avatar')  # 从FILES中获取文件
        
        print(f"收到更新请求 - 用户ID: {user.id}")
        print(f"name: {name}")
        print(f"bio: {bio}")
        print(f"avatar: {avatar}")
        
        # 更新用户信息
        if name:
            user.name = name
        if bio:
            user.bio = bio
        if avatar:
            # 删除旧头像（但不删除默认头像）
            if user.avatar and user.avatar.name != 'avatars/default.png':
                try:
                    user.avatar.delete(save=False)
                    print(f"已删除旧头像: {user.avatar.name}")
                except Exception as e:
                    print(f"删除旧头像失败: {str(e)}")
            user.avatar = avatar
            print(f"头像已更新: {avatar.name}")
        
        user.save()
        
        # 返回更新后的用户数据
        user_data = UserSerializer(user, context={'request': request}).data
        
        return Response({
            'success': True,
            'message': '资料更新成功！',
            'data': user_data
        })
        
    except Exception as e:
        print(f"更新失败: {str(e)}")
        return Response({
            'success': False,
            'message': f'更新失败: {str(e)}'
        }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def change_password(request, user_id):
    """修改密码"""
    if request.user.id != user_id:
        return Response({
            'success': False,
            'message': '无权限修改其他用户密码'
        }, status=status.HTTP_403_FORBIDDEN)
    
    serializer = ChangePasswordSerializer(data=request.data)
    
    if not serializer.is_valid():
        return Response({
            'success': False,
            'message': '验证失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)
    
    user = request.user
    if not user.check_password(serializer.validated_data['old_password']):
        return Response({
            'success': False,
            'message': '旧密码错误'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    user.set_password(serializer.validated_data['new_password'])
    user.save()
    
    return Response({
        'success': True,
        'message': '密码修改成功！'
    })


@api_view(['GET'])
@permission_classes([AllowAny])
def get_user_stats(request, user_id):
    """获取用户统计信息"""
    try:
        user = User.objects.get(id=user_id)
        
        # 统计数据
        from stories.models import Story
        stories = Story.objects.filter(author=user)
        published_stories = stories.filter(status='published')
        draft_stories = stories.filter(status='draft')
        
        total_views = sum(story.views for story in stories)
        total_likes = sum(story.likes for story in stories)
        total_comments = sum(story.comments.count() for story in stories)
        
        return Response({
            'success': True,
            'data': {
                'stories_count': stories.count(),
                'total_likes': total_likes,
                'total_views': total_views,
                'total_comments': total_comments,
                'published_stories': published_stories.count(),
                'draft_stories': draft_stories.count()
            }
        })
    except User.DoesNotExist:
        return Response({
            'success': False,
            'message': '用户不存在'
        }, status=status.HTTP_404_NOT_FOUND)


@api_view(['POST'])
@permission_classes([AllowAny])
def refresh_token(request):
    """刷新Token"""
    refresh_token = request.data.get('refresh')
    if not refresh_token:
        return Response({
            'success': False,
            'message': '缺少refresh token'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        refresh = RefreshToken(refresh_token)
        return Response({
            'success': True,
            'data': {
                'token': str(refresh.access_token)
            }
        })
    except Exception as e:
        return Response({
            'success': False,
            'message': 'Token无效或已过期'
        }, status=status.HTTP_401_UNAUTHORIZED)
